package com.lp.chapter001.service.easyexcel.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.excel.EasyExcel;
import com.lp.chapter001.excel.easyexcel.EasyExcelImportExcel;
import com.lp.chapter001.excel.easypoi.EasypoiExcel;
import com.lp.chapter001.excel.easypoi.EasypoiImportExcel;
import com.lp.chapter001.exception.BizException;
import com.lp.chapter001.handler.easyexcel.EasyExcelStudentImportHandler;
import com.lp.chapter001.handler.easyexcel.EasyExcelTotalNumImportHandler;
import com.lp.chapter001.handler.easypoi.EasypoiStudentImportHandler;
import com.lp.chapter001.handler.easypoi.EasypoiTotalNumImportHandler;
import com.lp.chapter001.service.easyexcel.EasyExcelService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;


/**
 * @author LP to 2024/03/30
 */
@Service
@Slf4j
@AllArgsConstructor
public class EasyExcelServiceImpl implements EasyExcelService {

    private final ApplicationContext applicationContext;

    /**
     * 导入
     * @author LP to 2024/03/30
     */
    @Override
    public void easyExcelImport(MultipartFile file) {
        try {
            long startTime = System.currentTimeMillis();
            // 读取总条数:这里会消耗一定时间。提供读取总条数方法，示例实际没有用到。这里也可以大概测出easyExcel读取文件的速度
            EasyExcelTotalNumImportHandler<EasyExcelImportExcel> totalNumListener = new EasyExcelTotalNumImportHandler<>();
            EasyExcel.read(file.getInputStream(), EasyExcelImportExcel.class, totalNumListener).sheet().doRead();
            log.info("总条数:{},解析文件总耗时/ms:{}", totalNumListener.getTotalRow(), (System.currentTimeMillis() - startTime));
            startTime = System.currentTimeMillis();
            // 实际处理数据
            EasyExcelStudentImportHandler listener = applicationContext.getBean(EasyExcelStudentImportHandler.class);
            EasyExcel.read(file.getInputStream(), EasyExcelImportExcel.class, listener)
                    .sheet().doRead();
            log.info("解析文件 + 处理数据总耗时/ms:{}", System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            throw new BizException("导入异常");
        }
    }
}
